/**
 * 
 */
package com.tech.freak.pyp;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.util.Log;
import android.widget.RemoteViews;

/**
 * @author julian
 *
 */
public class PyPAppWidgetProvider extends AppWidgetProvider {

	private static final String TAG = "PyPWdiget";
	/* (non-Javadoc)
	 * @see android.appwidget.AppWidgetProvider#onUpdate(android.content.Context, android.appwidget.AppWidgetManager, int[])
	 */
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		Log.d(TAG,"onUpdate");
		final int N = appWidgetIds.length;
		if(N==1){
			activateReceiver(context);
		}
        for (int i=0; i<N; i++) {
            int appWidgetId = appWidgetIds[i];
            String city = Utils.getWidgetInfo(context,appWidgetId, Utils.CITY);
            String license = Utils.getWidgetInfo(context, appWidgetId, Utils.LICENSE);
            updatePyPWidget(context, appWidgetManager, appWidgetId, city,license);
        }
	}
	
	static void updatePyPWidget(Context context,
			AppWidgetManager appWidgetManager, int appWidgetId, String city,
			String license) {
		Log.d(TAG,"updatePyPWidget");
		boolean pyp=false;
		pyp = Utils.calculatePyP(context, city, license);
		
		// Construct the RemoteViews object.  It takes the package name (in our case, it's our
        // package, but it needs this because on the other side it's the widget host inflating
        // the layout from our package).
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.pyp_appwidget);
        Resources res = context.getResources();
		if(pyp){
			views.setTextViewText(R.id.pyp_label, context.getString(R.string.pypLabel));
			if(city.equalsIgnoreCase(Utils.BOGOTA)){
				views.setImageViewResource(R.id.pyp_icon, R.drawable.bogota_sad);
				String [] pypArray = res.getStringArray(R.array.pypbogota);
				String text = Utils.getLicenseText(pypArray);
				views.setTextViewText(R.id.pyp_label, text);
			}else if (city.equalsIgnoreCase(Utils.MEDELLIN)){
				views.setImageViewResource(R.id.pyp_icon, R.drawable.medellin_sad);
				String [] pypArray = res.getStringArray(R.array.pypmedellin);
				String text = Utils.getLicenseText(pypArray);
				views.setTextViewText(R.id.pyp_label, text);
			}
		}else{
			views.setTextViewText(R.id.pyp_label, context.getString(R.string.no_pyplabel));
			if(city.equalsIgnoreCase(Utils.BOGOTA)){
				views.setImageViewResource(R.id.pyp_icon, R.drawable.bogota_happy);
				String [] pypArray = res.getStringArray(R.array.pypbogota);
				String text = Utils.getLicenseText(pypArray);
				views.setTextViewText(R.id.pyp_label, text);
			}else if (city.equalsIgnoreCase(Utils.MEDELLIN)){
				views.setImageViewResource(R.id.pyp_icon, R.drawable.medellin_happy);
				String [] pypArray = res.getStringArray(R.array.pypmedellin);
				String text = Utils.getLicenseText(pypArray);
				views.setTextViewText(R.id.pyp_label, text);
			}
		}
		
		// Tell the widget manager
        appWidgetManager.updateAppWidget(appWidgetId, views);
	}

    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        Log.d(TAG, "onDeleted");
        // When the user deletes the widget, delete the preference associated with it.
        final int N = appWidgetIds.length;
        if(N==1){
        	deactivateReceiver(context);
        }
        for (int i=0; i<N; i++) {
            Utils.deleteWidgetInfo(context, appWidgetIds[i]);
        }
    }
    
    @Override
    public void onEnabled(Context context) {
        Log.d(TAG, "onEnabled");
        activateReceiver( context);
    }

    private void activateReceiver(Context context) {
    	Log.d(TAG,"activateReceiver");
    	// When the first widget is created, register for the TIMEZONE_CHANGED and TIME_CHANGED
        // broadcasts.  We don't want to be listening for these if nobody has our widget active.
        // This setting is sticky across reboots, but that doesn't matter, because this will
        // be called after boot if there is a widget instance for this provider.
        PackageManager pm = context.getApplicationContext().getPackageManager();
        pm.setComponentEnabledSetting(
        		new ComponentName("com.tech.freak.pyp", "com.tech.freak.pyp.DateChangedReceiver"),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
        context.sendBroadcast(new Intent().setAction(Utils.UPDATE_WIDGET));
        
     }

	@Override
    public void onDisabled(Context context) {

        Log.d(TAG, "onDisabled");
        deactivateReceiver(context);
        
    }

	private void deactivateReceiver(Context context) {
        Log.d(TAG, "deactivateReceiver");
        // When the first widget is created, stop listening for the TIMEZONE_CHANGED and
        // TIME_CHANGED broadcasts.
		PackageManager pm = context.getApplicationContext().getPackageManager();
        pm.setComponentEnabledSetting(
                new ComponentName("com.tech.freak.pyp", "com.tech.freak.pyp.DateChangedReceiver"),
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
        
        //Create the pending intent to update our widget
        Intent i = new Intent();
        i.setAction(Utils.UPDATE_WIDGET);
        PendingIntent updateWidgetIntent = PendingIntent.getBroadcast(context, 001, i , PendingIntent.FLAG_UPDATE_CURRENT);

        // Cancel the alarm
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        am.cancel(updateWidgetIntent);

        // Tell the user about what we did.
        Log.i(TAG, "Alarm Canceled ");
	}
}
